<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>星空</title>
    <style>
        body{
            margin: 0;
            background-color: #000;
        }
        canvas{
            display: block;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas"></canvas>
    <script>
        var c = document.getElementById('myCanvas');
        var ctx = c.getContext('2d');
        var w = c.width = window.innerWidth;
        var h = c.height = window.innerHeight;
        window.onresize = function(){
            w = c.width = window.innerWidth;
            h = c.height = window.innerHeight;
        }
        var sum  = 300;
        var p = [];
        function initp() {
            for(var i = 0; i < sum; i++){
                p.push({
                    x: Math.random()*w,
                    y: Math.random()*h,
                    r: Math.random()+0.2
                })
            }
          }
          initp();
       
        function draw(){
            // initp()
            ctx.beginPath();
            ctx.fillStyle = '#fff';
            for(var i = 0; i < sum; i++){
                ctx.moveTo(p[i].x,p[i].y)
                ctx.arc(p[i].x,p[i].y,p[i].r,0,2*Math.PI);
            }
            ctx.fill();
            blink()
        }
        draw();
        // setInterval(function(){
        //     initp();
        //     draw();
        // },50)
        function blink() {
            for(let i = 0; i < sum; i++){
                const s = Math.random() > 0.5 ? 1 : -1;
                p[i].r += s*0.2;
                if(p[i].r < 0) {
                    p[i].r = -p[i].r;
                    p[i].x = Math.random()*w;
                    p[i].y = Math.random()*h
                } else if (p[i].r > 1) {
                    p[i].r -= 0.2
                }
                // p.push(p[i].x,p[i].y,p[i].r,0,2*Math.PI)
            }
        }
        setInterval(function(){
            ctx.clearRect(0,0,w,h);
            // p=[];
            
            draw()
        },100)
    </script>
</body>
</html>